#-*-coding:utf-8-*-
import requests
from bs4 import BeautifulSoup

"""负责在南昌大学宿舍用电查询系统中爬取用电信息"""


def query_elec_fun(dom_num):
    '''
    该函数用于查询宿舍电费等信息
    以寝室号(字符串)为参数
    返回一个包含剩余电量、本月用电量、
    余额、读表时间、预计能用时间5个数据的字典
    '''
    arg = {'UserName': dom_num}
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.73 Safari/537.36'}

    try:
        # 获得响应对象
        dom_info_respon = requests.post(
            'http://222.204.3.210/ssdf/Account/LogOn', data=arg, headers=headers, timeout=8)
        # 将响应对象进行编码
        dom_info_respon.encoding = 'utf-8'
        # 使用BS的lxml解析器对响应对象的文字进行解析
        soup = BeautifulSoup(dom_info_respon.text, "lxml",
                             from_encoding="utf-8")
        # 找到第一个table标签
        raw_dom_info = soup.find("table")
        if raw_dom_info:
            dom_info = raw_dom_info.find_all("tr", limit=4)  # 得到一个列表
            li = []
            for i in dom_info:
                anwser = i.find_all("td", limit=2)[1]
                li.append(anwser.get_text(strip=True))
            # 读数时间
            raw_time = raw_dom_info.find("tr")
            check_time = raw_time.find_all("td", limit=4)[
                3].get_text(strip=True)

            new_reading = li[0]  # 最新读数
            used_elec = li[1]  # 已用电量
            remaining_money = li[2]  # 剩余电费
            remaining_elec = li[3]  # 剩余电量
            average = float(used_elec) / float(check_time[8:10])  # 日用电量平均值
            if float(remaining_elec) <= 0:
                remaining_time = u"0"
            else:
                if average > 0:
                    remaining_time = unicode(
                        int(round(float(remaining_elec) / average)))  # 剩余使用天数估计值
                else:
                    remaining_time = u">10"

            return ({"new_reading": new_reading, "used_elec": used_elec, "remaining_money": remaining_money, "remaining_elec": remaining_elec, "remaining_time": remaining_time, "check_time": check_time})
        else:
            return "NoFound"
    except:
        return "Timeout"
